jQuery(document)
		.ready(
				function() {
						
					var config=new RegClientConfig();
					var sourceUtils=new SourceUtils();
					var coordinateUtils=new CoordinateUtils();
					//we look at the query and see if there is a source id in it, if there is we can get the existing data source
					//if it doesn't exist then we'll display an error message
					var currentUrl=window.location.href;
					var sourceId=currentUrl.substring(currentUrl.lastIndexOf("/")+1, currentUrl.length);
					//alert('sourceId=|'+sourceId+"|");
					var tempSource;
					var tempSources;
					var regCoordinateSystems;
				//if no id in the url then we assume an add is called for
					
					if(sourceId!=''){
						//get the source
						jQuery.getJSON(config.registryAddSourceUrl+sourceId, function(sources) {
							//alert(config.registryAddSourceUrl+sourceId);
							tempSources=sources;
							if(sources.source.length==undefined || sources.source.length==0){
								$("#NoSourceIdExists").html("Error DAS Source does not exist in the registry");
							}else{
								//alert('pop tempSource');
								tempSource=sources.source[0];
								populateFieldsWithSource(tempSource);
								populateCoordinatesSelect(tempSource);
								populateCapabilitiesSelect(tempSource);
							}
						});
					}else{
						populateCoordinatesSelect(tempSource);
						populateCapabilitiesSelect(tempSource);
					}
					
						//set the we are doing something image in the ajaxLoaderSources div
						if ($('#coordinatesSelector').val() == '') {
							$("#coordinatesSelector").html(
									'<img src=\"' + 'http://www.dasregistry.org/img/ajax-loader.gif' + '\">');
						}
						
		
						$('#update').click(function() {
							  //alert('Handler for .click() called.');
							  update();
							});
						
						function update(){
							
							var methodString='POST';
							if(tempSource!=undefined){
								populateSourceWithFields(tempSource);
								methodString='PUT';//change to update instead of add
							}
							//var content = '{"total":1417,"end":1,"start":1,"source":[{"description":"ajax3 Description","uri":"DS_112","version":[{"uri":"DS_112","capability":[{"type":"das1:structure","queryUri":"http://das.sanger.ac.uk/das/structure/structure"}],"coordinates":[{"authority":"PDBresnum","content":"PDBresnum,Protein Structure","source":"Protein Structure","uri":"http://www.dasregistry.org/dasregistry/coordsys/CS_DS7","testRange":"1.10.8.10-SSG5-1"}],"prop":[{"name":"spec","value":"DAS/1.6E"},{"name":"leaseTime","value":"2011-09-28T17:23:59+0100"},{"name":"alertMe","value":"1"},{"name":"projectName","value":"test for windows"},{"name":"projectDesc","value":"windows test of image upload"},{"name":"projectIcon","value":"http://www.dasregistry.org/ProjectIcon?id=86"},{"name":"projectHome","value":"http://www.google.com"}],"created":"2005-03-21T16:33:59+0000"}],"title":"structure","maintainer":{"email":"andreas.prlic@gmail.com"}}]}';
							//need to set authorization now, works otherwise
							//var auth=make_base_auth("jw12@sanger.ac.uk", "blah");
							var auth=make_base_auth($('#username').val(), $('#password').val());
							//alert(JSON.stringify(tempSources));
							
							$.ajax({
								type: methodString,
								url: config.registryAddSourceUrl,// 'http://localhost:8080/regrest/das/sources/',//,
								dataType: 'application/json',
								data: JSON.stringify(tempSources),
								contentType: "application/json",
								beforeSend : function(req) {
							        req.setRequestHeader('Authorization', auth);
							    },
								success: function(sources, status){
//									$('#result_au').text(msg);
									//var response = sources.replace(/</g,"&lt;");//if xml use this
									$('#result').html("new response here"+response+'<br/>'+sourceUtils.displaySourcesDetails(response));
									//$('#result_au').html("new response here"+sources.source[0].uri+" "+status);
								},
								error: function(jqXHR, textStatus, errorThrown){
									$('#result').html("DAS response mesage="+jqXHR.responseText+"<br/>ERROR: Status="+textStatus+"<br/>Status text="+errorThrown);
								}
							});
							
						}
						
						function make_base_auth(user, pass) {
							  var tok = user + ':' + pass;
							  var hash = Base64.encode(tok);
							  return "Basic " + hash;
							};
					

							
							function populateFieldsWithSource(source){
								//alert("title="+source.title);
								$('#title').val(source.title);
								var versionUrl=sourceUtils.getOriginalDataSourceUri(source.version[0].capability);
								$('#uri').val(source.uri);
								$('#rootUri').val(versionUrl);
								$('#adminemail').val(source.maintainer.email);
								$('#description').val(source.description);
								$('#doc_href').val(source.docHref);
								$('#spec').val(sourceUtils.getProp("spec",source.version[0]));
							}
							
							function populateCoordinatesSelect(source){
								jQuery.getJSON(config.registryCoordinatesUrl, function(dascoordinatesystem) {
									if(dascoordinatesystem.coordinates.length==undefined || dascoordinatesystem.coordinates.length==0){
										$("#coordinatesSelector").html('');
									
										return text="No Coordinates returned for this query, so no coordinate systems selectable";
									}
									var writeCoordinatesSelector = new WriteCoordinatesSelector();
									regCoordinateSystems=dascoordinatesystem;
									$("#coordinatesSelector").html(
											//write navigation for left and right if rows specified
											writeCoordinatesSelector.writeCoordinatesSelector(dascoordinatesystem));
									
									var coords=source.version[0].coordinates;
									//alert(coords.length);
									var coordsArray=[];
									for(var i=0; i<coords.length; i++){
										var coordElement=coords[i].content;
										//alert(coordElement);
										coordsArray.push(coordElement);
									}
									
									 $("#coordinatesSelector").val(coordsArray);
																
								});
								
							
							}
							
							function populateCapabilitiesSelect(source){
								
								jQuery.getJSON(config.knownCapabilitiesUrl, function(capabilities) {
									if(capabilities.capability.length==undefined || capabilities.capability.length==0){
										$("#capabilitiesSelector").html('');
									
										return text="No Capabilities returned for this query, so no caps selectable";
									}
									var writeCapabilitiesSelector = new WriteCapabilitiesSelector();
									$("#capabilitiesSelector").html(
											//write navigation for left and right if rows specified
											writeCapabilitiesSelector.writeCapabilitiesSelector(capabilities));
									var caps=source.version[0].capability;
									var capsArray=[];
									for(var i=0; i<caps.length; i++){
										var capType=caps[i].type;
										//alert(capType);
										capsArray.push(capType);
									}
									
									 $("#capabilitiesSelector").val(capsArray);
									
								});
							
							}
							
							function populateSourceWithFields(source){
								//populate our source/version with the fields from the input form
								source.title=$('#title').val();
								//alert(source.title);
								source.uri=$('#uri').val();
								source.maintainer.email=$('#adminemail').val();
								source.description=$('#description').val();
								source.docHref=$('#doc_href').val();
								//for now we are only doing one version until we have a new database that will accept multiple versions per source - hibernate?
								sourceUtils.setPropInVersion("spec", $('#spec').val(), source.version[0]);
								 var multipleValues = $("#capabilitiesSelector").val() || [];
								 var rootUri=$('#rootUri').val();
								sourceUtils.setCapablities(multipleValues, source.version[0], rootUri);
								 var multipleCoords= $("#coordinatesSelector").val() || [];//we need a different sepea
								// alert("coords selector="+multipleCoords);
								coordinateUtils.setCoordinates(source.version[0], multipleCoords, regCoordinateSystems);
							}
							
							
});